define([
  'jquery',
  'EventBus',
  'token'
], function ($, EventBus) {

  (function init() {
    console.log('开始初始化 project_web');
    EventBus.emit('core:register:app', {
      name: 'tmzk_web', // 和微应用名称保持一致
      microApps: ['erdcloud_web', 'workflow_web', 'project_web'], // 微应用
      beforeCreate: function () {// 应用预处理：事件监听
        console.log('project_web: beforeCreate');
        // TODO 是否可以移除此配置
        window.ELCONF.feat.project = true;
        window.ELCONF.feat.projectGroup = true;
        eventSubscribe();
      },
      init: function (callback) {
        console.log('project_web: init');
        eventPublish();
        startApp(callback);
      },
      mounted: function () {
        console.log('project_web: mounted');
        // 全局公共样式引入
        $.el.util.writeCss(ELMP.resource('components/vxe-ui-plugin/style.min.css', 'lib'), '#wrap-all')
        $.el.util.writeCss(ELMP.resource('css/index.css', 'lib'), '#wrap-all')
        $.el.util.writeCss(ELMP.resource('css/vxe-table/index.css', 'lib'), '#wrap-all')
        $.el.util.writeCss(ELMP.resource('css/element-ui.css', 'lib'), '#wrap-all')

        EventBus.emit('app:project:loaded'); // 项目应用加载完成事件

      },
      // 应用开发的资源包key，在开发过程中使用本地资源包时，会从apps/resource文件夹下加载
      resources: [
        'tmzk_sys_notice',
        'tmzk_test'
      ],
      dashboard: {
        path: 'apps/resource/project_dashboard/',
        cards: [
          'projectAllProjectState', 'projectBudgetCostCompare',
          'projectBudgetShare', 'projectBurnDownChart',
          'projectCreatedResolved', 'projectCurrentState',
          'projectDefineCharts', 'projectInfo',
          'projectJoinedProjects', 'projectKeyTask',
          'projectMember', 'projectMilestone',
          'projectMyProjectProgress', 'projectPersonalView',
          'projectPersonalWork', 'projectProgress',
          'projectSubProjects', 'projectTypeChart',
          'projectTypeStateChart', 'projectView',
          'projectAgenda', 'projectManagement'
        ]
      },
      custom: true
    })
    console.log('初始化完成 project_web');
  })()

  function eventSubscribe() {
    var gloabRoute
    function handleMenu(code, show) {
      const menu = $(`.main-sub-menu.essipsis-inline[data-code="${code}"]`).parent()
      if (show) {
        menu.show()
      } else {
        // 如果在菜单跳转信息菜单
        if (gloabRoute.paths[1].code === code) {
          window.route.goto(
            `${ELMP.resource('project_info.html', 'tmzk_project_info')}?id=${$.el.project.currentId}&spm=m-2-30&tid=`,
            { useCache: false }
          )
        }
        menu.hide()
      }
    }
    EventBus.on('core:route:after:change', (action, route) => {
      gloabRoute = route
      let elList = document.querySelectorAll('.advancedSelect')
      elList.forEach(el => {
        el.remove()
      })
      setTimeout(() => {
        if (route.paths[0]?.code === 'project') {
          // 如果为子项目隐藏项目验收菜单
          if ($.el.project.current.parentId !== '-1') {
            handleMenu('sys_menu:tmzk_project_acceptance', false)
            handleMenu('sys_menu:projectCost', false)
          } else {
            handleMenu('sys_menu:tmzk_project_acceptance', true)
            //子项目 通用类，横向类的 不显示费用总览
            if ($.el.project.current.type == "4" || $.el.project.current.type == "2") {
              handleMenu('sys_menu:projectCost', false)
            } else {
              handleMenu('sys_menu:projectCost', true)
            }
          }
        }
      }, 0);
    })
    EventBus.on('core:prepare:complete', function () {
      require([ELMP.resource('global-search.js', 'project_app')], function (GlobalSearch) {
        GlobalSearch.init();
      });
    });

    window.route.beforeEnterHook({
      name: 'project-info-cache-hook',
      handler(next, to, from, params) {
        // 第一个判断是目标页面是项目空间，且来源不是项目空间的页面，第二个判断是项目空间跳转到项目空间，且不是点击使用引导
        if (to && (
          (to.indexOf('spm=m-2-30') !== -1 && from.indexOf('spm=m-2-30') === -1) && to.indexOf('apps') === -1 ||
          (to.indexOf('spm=m-2-30') !== -1 && from.indexOf('spm=m-2-30') !== -1 &&
            to.indexOf('id') !== -1 && from.indexOf('id') !== -1 &&
            from.indexOf('resource') === -1 && to.indexOf('resource') === -1 &&
            !(to.indexOf($.menu.getParam('id')) !== -1 && from.indexOf($.menu.getParam('id')) !== -1)
          )
        )) {
          // 禁用路由缓存
          params.$meta.useCache = false;
          // 跳转去项目信息
          let urlPath = ''

          _.each($.el.auth.resources, function (item) {
            if (item.code == 'project') {
              _.each(item.children, function (res) {
                if (res.code == 'project:info') {
                  let params = to.split('?')[1]

                  urlPath = res.href + '?' + params;
                }
              })
            }
          })
          to = urlPath;
        }
        next(to, from, params);
      }
    });

    // 统一流程处理页面
    EventBus.on('workflow:action:view:default:table:render', function (event, { objData, moduleName, $ctt }) {
      objData = objData || [];
      if (_.includes(['task', 'project', 'require', 'issue', 'risk'], moduleName)) {
        $.el.template($ctt, 'project-view-changeobj-list-table', {
          list: objData,
          count: objData.length,
          state: window.CACHE_.flowState,
          stateType: moduleName,
          height: '100%'
        });
      }
    });
    EventBus.on('workflow:action:handle:default:table:render', function (event, {
      objData = {}, $ctt, data = [], objDataSet = {}, moduleName = 'others', tplJson = ''
    }) {
      if (_.includes(['task', 'project', 'require', 'issue', 'risk'], moduleName)) {
        require([ELMP.resource('workflow-configs/util.js', 'project_app')], function (util) {
          util.renderWorkflowActionTable($ctt, data, objData, objDataSet, moduleName, tplJson);
        });
      }
    });
    EventBus.on('workflow:action:submit:default:table:render', function (event, {
      objData = {}, $ctt, data = [], objDataSet = {}, moduleName = 'others', tplJson = '', draft
    }) {
      if (_.includes(['task', 'project', 'require', 'issue', 'risk'], moduleName)) {
        require([ELMP.resource('workflow-configs/util.js', 'project_app')], function (util) {
          util.renderObjectListUsingViewTable($ctt, data, objData, objDataSet, moduleName, tplJson, draft);
        });
      }
    });
    $('body').on('click', '[data-enter-project]', function () {
      $.el.project.enterSpace($(this).attr('data-enter-project'));
    });
    EventBus.on('workflow:action:submit:default:table:render', function (event, {
      objData = {}, $ctt, data = [], objDataSet = {}, moduleName = 'others', tplJson = ''
    }) {
      require([ELMP.resource('workflow-configs/util.js', 'project_app')], function (util) {
        util.renderObjectListUsingViewTable($ctt, data, objData, objDataSet, moduleName, tplJson);
      })
    });
    $('body').on('click', '[data-enter-project]', function () {
      $.el.project.enterSpace($(this).attr('data-enter-project'));
    });
    // 注册渲染vue
    EventBus.on('core:form:section:custom:load', function (event, options) {
      if (/\.vue\?{0,}/.test(options.params.url)) {
        let url
        if (options.params.url.includes(',')) {
          const reg = /^resource:(.+)\,(.+)/.exec(options.params.url.replace(/\?.+/, ''))
          const module = reg[2]
          const address = reg[1]
          url = `component!@/${module}/${address}`
        } else {
          url = `component!${options.params.url.replace(/\?.+/, '')}`
        }
        require([url, 'vue', 'babel!' + ELMP.resource('store/index.js', 'lib')], function (app, Vue, store) {
          // 成功回调
          options.successFn('<div id="vue-container"></div>')
          new Vue({
            store,
            render: h => h(app)
          }).$mount('#vue-container')
        })
        options.preventDefault()
      }
    });
  }

  function eventPublish() {
    // 国际化key前缀
    EventBus.emit("core:register:config:i18nMapping", {
      task: 'task_',
      issue: 'issue_',
      risk: 'risk_',
      require: 'require_'
    });
    // 业务类型转换
    EventBus.emit("core:register:config:mapBusinessType", {
      ELRequire: 'require',
      ELRequirement: 'require',
      ELTask: 'task',
      ELRisk: 'risk',
      ELIssue: 'issue',
      ELProject: 'project',
      ELBudget: 'budget'
    });
    // 业务参数名转换
    EventBus.emit("core:register:config:mapBusinessParamName", {
      require: { checker: 'ELRequire', result: 'ELRequire' },
      requirement: { checker: 'ELRequire', result: 'ELRequire' },
      task: 'ELTask',
      plan: 'ELTask',
      risk: 'ELRisk',
      issue: 'ELIssue',
      project: 'ELProject',
      budget: 'ELBudget'
    });
    // 增加lifecycleTypes类型
    var lifecycleTypes = ['ELTask', 'ELIssue', 'ELRisk', 'ELRequire', 'ELProject'];
    EventBus.emit('core:register:config:lifecycleTypes', lifecycleTypes);
    // 生命周期LifecycleState映射
    EventBus.emit("core:register:config:mapLifecycleState", {
      'ELTask': 'task',
      'ELIssue': 'issue',
      'ELRisk': 'risk',
      'ELRequire': 'require',
      'ELProject': 'project'
    });
    // 业务对象对应的工作流执行处理页面函数
    EventBus.emit('workflow:register:config:ExecutionConfig', {
      'budget': ELMP.resource('workflow-configs/budget.js', 'project_app'),
      'issue': ELMP.resource('workflow-configs/issue.js', 'project_app'),
      'project': ELMP.resource('workflow-configs/project.js', 'project_app'),
      'proposal': ELMP.resource('workflow-configs/proposal.js', 'project_app'),
      'require': ELMP.resource('workflow-configs/requirement.js', 'project_app'),
      'risk': ELMP.resource('workflow-configs/risk.js', 'project_app'),
      'task': ELMP.resource('workflow-configs/task.js', 'project_app')
    });

    EventBus.emit("core:register:config:apiWhiteList", [
      /\w+:\/tmzk.+/,
      /PUT:(\/)?proj\/v1\/notify\/{0}/,
      /POST:(\/)?portfolio\/v1\/portfolio\/attention/,
      /POST:(\/)?proj\/v1\/addMyCareProject/,
      /POST:(\/)?proj\/v1\/notice\/get/,
      /POST:(\/)?sys\/v1\/view\/query\/{0}/,
      /POST:(\/)?proj\/v1\/projects\/ext/,
      /post:(\/)?sys\/v1\/resources\/role\/list/,
      /POST:(\/)?proj\/v1\/projects\/ext/,
      /POST:(\/)?proj\/v1\/doc\/doc/,
      /POST:(\/)?proj\/v1\/doc\/upload/,
      /PUT:(\/)?proj\/v1\/attachment\/objects\/list/,
      /POST:(\/)?proj\/v1\/config\/queryUserConfig/
    ]);

    EventBus.emit("core:register:config:sidePageClose", {
      initState: {
        docState: {
          id: '',
          folderId: '',
          obj: {},
          updateRow: false,  //单行刷新
          loadTable: false,  //刷新列表
          acls: {}
        },
        docHistoryState: {
          id: '',
          obj: {}
        },
        projectInitState: {
          projectId: '',
          updated: null,
          created: false,
          projectRequire: false,
          addCompetitor: false,
          competitorFlag: false,
          competitorId: '',
          addCustomer: false,
          customerId: ''
        }
      },
      callbacks: {
        'resource:form.html,project_doc': function (initState) {
          window.CACHE_.docForm = _.clone(initState.docState);
          window.CACHE_.docForm.id = window.CACHE_.idStack[0].id;
        },
        'resource:detail.html,project_doc': function (initState) {
          var acls = window.CACHE_.docForm.acls;
          window.CACHE_.historyForm = _.clone(initState.docHistoryState);
          window.CACHE_.docForm = _.clone(initState.docState);
          window.CACHE_.docForm.id = window.CACHE_.idStack[0].id;
          window.CACHE_.docForm.acls = acls;
        },
        'resource:form.html,project_plan': function (initState) {
          window.CACHE_.taskForm.taskId = window.CACHE_.idStack[0].id;
          window.CACHE_.taskForm.projectId = window.CACHE_.idStack[0].projectId;
          window.CACHE_.taskForm.projects = window.CACHE_.idStack[0].projects;
          window.CACHE_.taskForm.state = (window.CACHE_.idStack[0].object || {}).state;
        },
        'resource:form.html,project_issue': function (initState) {
          window.CACHE_.issueForm = _.clone(initState.projectInitState);
          window.CACHE_.issueForm.issueId = window.CACHE_.idStack[0].id;
          window.CACHE_.issueForm.projectId = window.CACHE_.idStack[0].projectId;
        },
        'resource:form.html,project_requirement': function (initState) {
          window.CACHE_.reqForm = _.clone(initState.projectInitState);
          window.CACHE_.reqForm.id = window.CACHE_.idStack[0].id;
          window.CACHE_.reqForm.projectId = window.CACHE_.idStack[0].projectId;
        },
        'resource:form.html,project_risk': function (initState) {
          window.CACHE_.riskForm = _.clone(initState.projectInitState);
          window.CACHE_.riskForm.riskId = window.CACHE_.idStack[0].id;
          window.CACHE_.riskForm.projectId = window.CACHE_.idStack[0].projectId;
        },
        'resource:baseline/plan/form.html,project_project': function (initState) {
          window.CACHE_.taskForm = _.clone(initState.projectInitState);
          window.CACHE_.taskForm.taskId = window.CACHE_.idStack[0].id;
          window.CACHE_.taskForm.projectId = window.CACHE_.idStack[0].projectId;
          window.CACHE_.taskForm.projects = window.CACHE_.idStack[0].projects;
        },
        'resource:baseline/require/form.html,project_project': function (initState) {
          window.CACHE_.reqForm = _.clone(initState.projectInitState);
          window.CACHE_.reqForm.id = window.CACHE_.idStack[0].id;
          window.CACHE_.reqForm.projectId = window.CACHE_.idStack[0].projectId;
        }
      }
    });
    EventBus.emit("core:register:config:abortRequest", { // 页面切换时取消未处理完成的ajax请求
      eventElements: [], // 触发取消的点击事件触发对象，目前关注通过data-load, data-section触发的页面切换
      whitelist: [
        'GET:/proj/v1/projects',
        'GET:/proj/v1/getMyCareProject'
      ] // 不可被取消的请求。可以是正则也可以是字符串。如果是字符串使用包含关系处理；如果是正则使用正则匹配请求
    });
    // 系统配置
    EventBus.emit("core:register:config:systemConfigHacker", {
      allowProjectState: {
        resource: 'project_app',
        filename: 'configs/js/allow-config.js'
      },
      task: {
        resource: 'project_app',
        filename: 'configs/js/export-config.js'
      },
      require: {
        resource: 'project_app',
        filename: 'configs/js/export-config.js'
      },
      issue: {
        resource: 'project_app',
        filename: 'configs/js/export-config.js'
      },
      risk: {
        resource: 'project_app',
        filename: 'configs/js/export-config.js'
      },
      project: {
        resource: 'project_app',
        filename: 'configs/js/export-config.js'
      }
    });

    // 自动登录
    EventBus.emit('core:register:config:autoLogin', function (params, callback) {
      window.token.autoRefresh = false;
      const accessToken = $.el.util.getHashParam('token');
      if (accessToken) {
        window.self.token.setToken(
          {
            accessToken: accessToken,
            refreshToken: 'undefined',
            refreshTokenTimeout: +new Date() + 60 * 60 * 24 * 1000 * 30,
          },
          new Date().getTime()
        );
      }
      callback();
    })

    // 页面跳转处理
    EventBus.emit("core:register:config:pageJump", {
      menuCheck: function (url, params, menu, subMenu) {
        return menu.code === 'project';
      },
      process: function (url, params, menu, subMenu, callback) {
        $.el.project.promise(function () {
          if (!params.pid || !_.some($.el.project.projects, { id: params.pid })) {
            $.el.project.setCurrent(null);
            callback(ELMP.resource('project_list.html', 'project_project'), null, menu);
          } else {
            $.el.project.setCurrent(params.pid);
            callback(url, { id: params.pid, spm: 'm-2-' + menu.id, tid: menu.tid }, menu);
          }
          // 将一级菜单设为选中
          $('[data-code="' + menu.code + '"]', '#sidebar-menu')
            .parent().addClass('active').siblings().removeClass('active');
        });
      }
    });
    // 工作流配置：发起流程页面屏蔽项目
    EventBus.emit("app:workflow:config:extends", "blockedCategoriesAtCreate", [
      'ELProject'
    ]);
    // 工作流配置：使用老页面（workflow_action/submit.html index.html）的流程
    EventBus.emit("app:workflow:config:extends", "dangerousUseWorkflowActionPageInsteadOfSdk", [
      'DOUSON_TR_NEW', 'DOUSON_DCP_NEW'
    ]);

    // PPM离职人员遗留事项处理页面
    EventBus.emit("core:register:config:legacyMatters", [function projectLegacy(resolve) {
      require([ELMP.resource('js/index.js', 'project_legacy')], resolve);
    }]);

    EventBus.emit('workflow:register:config:ExecutionLayout', {
      // 项目变更流程
      'others-PROJECT_CHANGE': function (callback) {
        callback(ELMP.resource('workflow/index.html', 'project_change'))
      }
    })
    // 产品信息遗留事项
    EventBus.emit('core:register:config:legacyMatters', [function productLegacy(resolve) {
      require([ELMP.resource('js/project_product-legacy.js', 'project_product')], resolve)
    }])

    EventBus.emit('workflow:register:config:ExecutionLayout', {
      'others-DOUSON_DCP_NEW': function (callback) {
        callback(ELMP.resource('process_form/dousonDCP/index.html', 'project_review'))
      },
      'others-DOUSON_TR_NEW': function (callback) {
        callback(ELMP.resource('process_form/dousonTR/index.html', 'project_review'))
      }
    });
    // 流程表单注册
    EventBus.emit('workflow:register:config:ExecutionLayout', {
      // 流程分类编码 + 流程定义key + 单个节点Key（可选）
      // 需求审批 挂载全局业务对象  (因为启动页面用的系统公共启动页面 所以挂载时除了启动节点其他节点都需要挂载)
      'ELRequire-PPM_REQUIRE_SUBMIT': function (callback) {
        callback(ELMP.resource('workflow_requirement/process_steps.html', 'tmzk_workflow'));
      },
    });

    require([ELMP.resource('auth_manage.js', 'project_auth_manage')], function (module) {
      module.init()
    });

    EventBus.on('core:prepare:complete', function () {
      $.el.get({
        url: ELMP.getUrl('/proj/v1/user/me'),
        success(res) {
          var data = res.res
          $.auth.pushAcl('system', data.acls);
        }
      })
    })
  }

  function startApp(callback) {
    const babel = ELMP.resource('plugins/transform3/babel.js', 'lib').replace('.js', '')
    const component = ELMP.resource('plugins/transform3/component.js', 'lib').replace('.js', '')
    require.config({
      paths: {
        'babel': babel,
        'component': component
      },
    });
    require([ELMP.resource('start.js', 'project_app'), ELMP.resource('plugins/index.js', 'lib')], function (start, plugins) {
      plugins.init()
      start(callback);
    });
  }
})
